package com.dyna.gateway.adapter;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.web.MockHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.net.InetSocketAddress;

/**
 * ServletHttpRequest适配HttpServletRequest
 */
public class ServerHttpRequestAdapter {

    public static HttpServletRequest adapt(ServerHttpRequest serverRequest) {
        MockHttpServletRequest mockRequest = new MockHttpServletRequest();
        mockRequest.setRequestURI(serverRequest.getPath().toString());
        mockRequest.setMethod(serverRequest.getMethodValue());

        // 设置请求头
        serverRequest.getHeaders().forEach((headerName, headerValues) -> {
            for (String headerValue : headerValues) {
                mockRequest.addHeader(headerName, headerValue);
            }
        });

        // 设置远程地址
        InetSocketAddress remoteAddress = serverRequest.getRemoteAddress();
        if (remoteAddress != null) {
            mockRequest.setRemoteAddr(remoteAddress.getAddress().getHostAddress());
            mockRequest.setRemotePort(remoteAddress.getPort());
        }

        return mockRequest;
    }
}